# coding=utf-8
##
## Author: jmdvirus@aliyun.com
##
## Create: 2019年02月18日 星期一 11时14分41秒
##
import numpy as np
import cv2
from sklearn import datasets
from sklearn import model_selection
from sklearn import metrics
import matplotlib.pyplot as plt

def load_data():
    iris = datasets.load_iris()
    #print("iris: ", iris)
    print("iris.shape: ", iris.data.shape)
    print("iris target: ", iris.target)
    return iris

def fetch_data(odata):
    idx = odata.target != 2
    data = odata.data[idx].astype(np.float32)
    target = odata.target[idx].astype(np.float32)
    return (data, target)

def show(odata, data, target):
    plt.scatter(data[:, 0], data[:, 1], c=target,
            cmap=plt.cm.Paired, s=100)
    plt.xlabel(odata.feature_names[0])
    plt.ylabel(odata.feature_names[1])

def train(odata, data, target):
    x_train, x_test, y_train, y_test = model_selection.train_test_split(
            data, target, test_size=0.1, random_state=42)

    print("x_train: ", x_train)
    print("x_test: ", x_test)

    lr = cv2.ml.LogisticRegression_create()
    lr.setTrainMethod(cv2.ml.LogisticRegression_MINI_BATCH)
    lr.setMiniBatchSize(1)

    lr.setIterations(1000)
    print("training...")
    lr.train(x_train, cv2.ml.ROW_SAMPLE, y_train)
    y = lr.get_learnt_thetas()
    print("out: ", y)

    print("test on train ...")
    ret, y_pred = lr.predict(x_train)
    x = metrics.accuracy_score(y_train, y_pred)
    print("on train out: ", x)

    ret, y_pred = lr.predict(x_test)
    x = metrics.accuracy_score(y_test, y_pred)
    print("on test out: ", x)

if __name__ == "__main__":
    data = load_data()
    d, t = fetch_data(data)
    show(data, d, t)
    train(data, d, t)
    #plt.show()


